﻿using System;
using System.Collections.Generic;
using Pharmacy.Ultilities;
using Pharmacy.ExceptionHandling;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPrinting;
using DevExpress.XtraGrid.Export;
using DevExpress.XtraExport;
using DevExpress.XtraEditors.Repository;
using System.Drawing;
using DevExpress.XtraGrid;
using System.Data.Objects.DataClasses;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using Pharmacy.Ultilities.BaseEventArgs;

namespace PharmacyPharnet.Core
{
    public partial class FrmListBase : DialogViewBase
    {
        #region Declarations
        /// <summary>
        /// Current entity to load data 
        /// </summary>
        public string PersistentType
        {
            get;
            set;
        }

        public delegate void RowSelectedEventHandler(object sender, RowSelectedArgs e);
        public event RowSelectedEventHandler RowSelected = null;
        #endregion

        #region Constructors
        public FrmListBase()
        {
            InitializeComponent();
        }
        #endregion        

        #region Override Methods
        
        #endregion

        #region Custom Methods
        public void LoadLayoutGrid()
        {
            if (!string.IsNullOrEmpty(PersistentType))
            {
                string fileXMLName = PersistentType;
                string path = IOHelper.CombinePath(IOHelper.ExecutePath, string.Format(@"ListSchemaMasterData\{0}.xml", fileXMLName));
                grvMasterData.RestoreLayoutFromXml(path);

                // Set image for Delete button
                Image img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\delete.png"));
                btnDelete = grvMasterData.Columns[1].ColumnEdit as RepositoryItemButtonEdit;
                btnDelete.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                btnDelete.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero);

                // Set image for Edit button
                img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\edit.png"));
                btnEdit = grvMasterData.Columns[0].ColumnEdit as RepositoryItemButtonEdit;
                btnEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                btnEdit.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero);
            }
        }

        private void OpenFile(string fileName)
        {
            if (MessageBox.Show("Do you want to open this file?", "Export File", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName = fileName;
                    process.StartInfo.Verb = "Open";
                    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    process.Start();
                }
                catch (Exception ex)
                {
                    string message = "Cannot find an application on your system suitable for openning the file with exported data.";
                    ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                    MessageBox.Show(message);
                }
            }
        }

        private string ShowSaveFileDialog(string title, string filter)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            string name = Application.ProductName;
            int n = name.LastIndexOf(".") + 1;
            if (n > 0) name = name.Substring(n, name.Length - n);
            dlg.Title = "Export To " + title;
            //dlg.FileName = name;
            dlg.FileName = "filename";
            dlg.Filter = filter;
            if (dlg.ShowDialog() == DialogResult.OK) return dlg.FileName;
            return "";
        }

        //IExportProvider provider
        private void ExportTo(GridView currentView, string fileName)
        {
            grdMasterData.FindForm().Refresh();
            currentView.OptionsPrint.PrintDetails = true;
            currentView.OptionsPrint.ExpandAllDetails = true;
            currentView.OptionsPrint.ExpandAllGroups = true;
            currentView.OptionsPrint.AutoWidth = false;
            XlsExportOptions option = new XlsExportOptions();
            option.ShowGridLines = true;
            currentView.ExportToXls(fileName, option);
        }

        private void ExportToExcelWithoutDetail(GridView currentView, string fileName)
        {
            grdMasterData.FindForm().Refresh();
            if (currentView == null) return;
            GridViewExportLink gvlink;
            using (ExportXlsProvider provider = new ExportXlsProvider(fileName))
            {
                gvlink = (GridViewExportLink)currentView.CreateExportLink(provider);
                gvlink.ExpandAll = true;
                gvlink.ExportDetails = true;
                gvlink.ExportAll = true;
                gvlink.ExportTo(true);
            }
        }
        #endregion

        #region Event Handlers
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = ShowSaveFileDialog("Microsoft Excel Document", "Microsoft Excel|*.xls");
                if (fileName != "")
                {
                    //new ExportXlsProvider(fileName)
                    //ExportTo(this.MainView as GridView, fileName);
                    //ExportTo(fileName);
                    string msg = Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.EXPORTDATA_INCLUDEDETAIL);
                    if (MessageBox.Show(msg, Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.EXPORTDATA_MESSAGETITLE), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        ExportTo(grvMasterData, fileName);
                    }
                    else
                    {
                        ExportToExcelWithoutDetail(grvMasterData, fileName);
                    }
                    OpenFile(fileName);
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void FrmListBase_Load(object sender, EventArgs e)
        {
            try {
                LoadLayoutGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        private void grvMasterData_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            try
            {
                if (e.Info.IsRowIndicator)
                {
                    if (e.RowHandle != GridControl.NewItemRowHandle && e.RowHandle != GridControl.AutoFilterRowHandle)
                    {
                        if (e.RowHandle < 0)
                        {
                            e.Info.DisplayText = "";
                        }
                        else
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    }
                    if (e.RowHandle == GridControl.AutoFilterRowHandle)
                    {
                        e.Info.ImageIndex = -1;
                        e.Info.DisplayText = "Filter";
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }
        #endregion        

        private void grdMasterData_DoubleClick(object sender, EventArgs e)
        {
            EntityObject item = grvMasterData.GetRow(grvMasterData.FocusedRowHandle) as EntityObject;
            if (item == null)
            {
                return;
            }
            GridHitInfo ghi = grvMasterData.CalcHitInfo((e as MouseEventArgs).Location);
            if (!ghi.InRow)
            {
                return;
            }

            RowSelectedArgs args = new RowSelectedArgs();
            args.CurrentSelectedRowID = Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value);
            if (RowSelected != null)
            {
                RowSelected(sender, args);
                this.Close();
            }
            
            
        }
    }
}
